<template>
    <nly-content-wrapper>
        <nly-content-header>
            <nly-row class="col-12">
                <nly-row class="col-12 ">
                    <nly-col xs="12" sm="12" md="12" lg="9" xl="9" class="form-inline" style="justify-content: left;">
                        <nly-row class="ml-1 mb-2 lr mt-4" v-show="show">
                            <nly-col xs="12" sm="12" md="12" lg="12" xl="12" class="form-inline" style="justify-content: left;">
                                <form-input title="客户名称" id="crmName" labelStyle rightStyle="width:120px;" class="ml-2" v-show="show" :v-model="postData.crmName"></form-input>
                                <form-input title="报价编号" id="quotedPriceCode" labelStyle rightStyle="width:120px;" class="ml-2" v-show="show" :v-model="postData.quotedPriceCode"></form-input>
                                <form-input title="报价人" id="quotedPriceBy" labelStyle rightStyle="width:120px;" class="ml-2" v-show="show" :v-model="postData.quotedPriceBy"></form-input>
                                <form-select title="状态" class="ml-2" rightStyle="width:120px;" v-show="show" :v-model="postData.status" :dataList="[
                { key: 0, title: '正常' },
                { key: 2, title: '删除' }
              ]"></form-select>
                            </nly-col>
                        </nly-row>
                    </nly-col>
                    <nly-col xs="12" sm="12" md="12" lg="3" xl="3" class="form-inline align-self-start" style="justify-content: right;">
                        <nly-button-group>
                            <nly-button variant="info" @click="PageList" button-class="mr-2">查询</nly-button>
                            <nly-button variant="info" button-class="mr-2" @click="reset">重置</nly-button>
                            <nly-button @click="showFunction" variant="info" button-class="mr-2">
                                <i name="xx" :class="show ? 'fas fa-angle-down mr-1' : 'fas fa-angle-up mr-1'" />
                                {{ show ? "折叠" : "展开" }}
                            </nly-button>
                        </nly-button-group>
                    </nly-col>
                </nly-row>

            </nly-row>
            <nly-container fluid></nly-container>
        </nly-content-header>
        <div class="tabpanel_tab_spacer"></div>
        <div>
            <a-button type="primary" class="crm-btn" v-if="editBtnShow">编辑</a-button>
            <a-button type="primary" class="crm-btn" v-if="disableBtnShow">删除</a-button>
            <a-button type="primary" class="crm-btn" @click="AddItem" v-if="addBtnShow">新增</a-button>
        </div>
        <nly-content>
            <!-- 列表 -->
            <a-table :columns="columns" :components="components" :data-source="data" :scroll="{ y: 500}" bordered :pagination="true">
                <a slot="crmName" slot-scope="text, record" @click="goToDetail(record)" class="goToDetail">
                    {{record.crmName}}
                </a>
                <a slot="quotedPriceCode" slot-scope="text, record" @click="showModal(record)" class="goToDetail">
                    {{text}}
                </a>
            </a-table>
            <!-- modal 弹窗  -->
            <a-modal ref="edit-modal" :visible="editModal" lg hide-footer :footer="null" :title="editItem.id ? '编辑' : '新增'" size="xl" @calcel="hideModal">
                <div id="components-form-demo-advanced-search">
                    <a-form class="ant-advanced-search-form" :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 24 }" @submit="handleSubmit">
                        <div class="line" style="color:#1980Ff;font-size:15px;">基本信息</div>
                        <a-row :gutter="24">
                            <a-col :span="10">
                                <a-form-item label="客户名称">
                                    <a-input v-decorator="['userName', { rules: [{ required: true, message: '客户名称不能为空' }] }]" placeholder="请输入客户名称" :disabled="isDisabled" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="10" :push="2" :style="isShow">
                                <a-form-item label="报价编号">
                                    <a-input v-decorator="['password', { rules: [{ required: true, message: '报价编号不能为空' }] }]" placeholder="请输入报价编号" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="10">
                                <a-form-item label="*报价人" :validate-status="validateStatus" :help="errorMsg">
                                    <a-input-search placeholder="请选择报价人" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="10" :push="2">
                                <a-form-item label="报价时间">
                                    <a-date-picker show-time format="YYYY-MM-DD HH:mm" placeholder="报价时间" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="22" :pull="3">
                                <a-form-item label="附件上传">
                                    <div>
                                        <a-upload :action="this.$Global.ApiBaseUrl + '/uploadFile'" list-type="picture" :multiple="true" :fileList="fileList" :headers="header" @change="uploadFile">
                                            <a-button>
                                                <a-icon type="upload" />点击上传
                                            </a-button>
                                        </a-upload>
                                    </div>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="22" :pull="3">
                                <a-form-item label="备注">
                                    <a-textarea placeholder="请输入用户备注" :rows="5" v-decorator="['remarks', { rules: [{ required: false, message: '' }] }]" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <div class="line" style="color:#1980Ff;font-size:15px;">报价明细</div>
                        <a-table style="min-height:200px" bordered :data-source="detailData" :columns="detailColumns" :pagination="false" :components="detailComponents">
                            <template v-for="col in ['commodityName', 'price', 'discount', 'counts', 'specs', 'totalPrice']" :slot="col" slot-scope="text, record">
                                <div data-key="">
                                    <a-textarea style="margin: -5px 0" @change="e => onCellChange(record.key, col, e.target.value)" />
                                </div>
                            </template>
                            <template slot="operation" slot-scope="text, record">
                                <a-popconfirm title="确定要删除?" @confirm="() => onDelete(record.key)"></a-popconfirm>
                                <a href="javascript:;" @click="onDelete(record.key)">删除</a>
                            </template>
                        </a-table>
                        <a-button class="editable-add-btn" @click="handleAdd">新增明细</a-button>
                        <a-row>
                            <a-col :span="24" :style="{ textAlign: 'right' }">
                                <a-button type="primary" html-type="submit">保存</a-button>
                                <a-button :style="{ marginLeft: '8px' }" @click="handleReset">重置</a-button>
                                <a-button :style="{ marginLeft: '8px' }" @click="hideModal">关闭</a-button>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
            </a-modal>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>
import { mapState } from "vuex";
import { save, priceList, disable, enable, deletePrice } from "@/api/crm/price";
import { listToMap } from "@/utils/tool/map";
import { components } from "@/utils/antTableComponents";
import Vue from "vue";

/**
 * 机构数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const officeListToTree = (list, childrenOffice, parentId) => {
    list.forEach(item => {
        // 判断是否为父级菜单
        if (item.parentId == parentId) {
            const child = {
                ...item,
                title: item.name,
                key: item.id,
                children: []
            };
            // 迭代 list， 找到当前菜单相符合的所有子菜单
            officeListToTree(list, child.children, item.id);
            // 删掉不存在 children 值的属性
            if (child.children.length <= 0) {
                delete child.children;
            }
            // 加入到树中
            childrenOffice.push(child);
        }
    });
};

export default {
    props: {
        customerId: {
            type: Number,
            default: null
        },
        customer: {
            type: Object,
            default: () => ({})
        }
    },
    data () {
        const detailColumns = [
            {
                title: "商品名称",
                dataIndex: "commodityName",
                key: "commodityName",
                width: 120,
                scopedSlots: { customRender: "commodityName" }
            },
            {
                title: "商品价格(元)",
                dataIndex: "price",
                key: "price",
                width: 120,
                scopedSlots: { customRender: "price" }
            },
            {
                title: "折扣(元)",
                dataIndex: "discount",
                key: "discount",
                width: 120,
                scopedSlots: { customRender: "discount" }
            },
            {
                title: "数量",
                dataIndex: "counts",
                key: "counts",
                width: 120,
                scopedSlots: { customRender: "counts" }
            },
            {
                title: "规格",
                dataIndex: "specs",
                key: "specs",
                width: 120,
                scopedSlots: { customRender: "specs" }
            },
            {
                title: "总金额",
                dataIndex: "totalPrice",
                key: "totalPrice",
                width: 120,
                scopedSlots: { customRender: "totalPrice" }
            },
            {
                title: "操作",
                dataIndex: "operation",
                key: "operation",
                width: 120,
                scopedSlots: { customRender: "operation" }
            }
        ];
        const columns = [
            {
                title: "报价编号",
                dataIndex: "quotedPriceCode",
                key: "quotedPriceCode",
                width: 120,
                scopedSlots: { customRender: "quotedPriceCode" }
            },
            {
                title: "客户名称",
                dataIndex: "crmName",
                key: "crmName",
                width: 120,
                scopedSlots: { customRender: "crmName" }
            },
            {
                title: "报价人",
                dataIndex: "quotedPriceBy",
                key: "quotedPriceBy",
                width: 120
            },
            {
                title: "报价时间",
                dataIndex: "quotedPriceDate",
                key: "quotedPriceDate",
                width: 120
            },
            {
                title: "创建人",
                dataIndex: "createUserName",
                key: "createUserName",
                width: 80
            },
            {
                title: "修改时间",
                dataIndex: "updateDate",
                key: "updateDate",
                width: 120
            },
            {
                title: "状态",
                dataIndex: "status",
                key: "status",
                width: 120,
                customRender: (text, row, index) => {
                    return text == 2 ? (
                        <nly-badge bg-variant="danger">删除</nly-badge>
                    ) : (
                        <nly-badge bg-variant="success">正常</nly-badge>
                    );
                }
            },
            {
                title: "操作",
                dataIndex: "o",
                width: 200,
                key: "o",
                customRender: (text, row, index) => {
                    return (
                        <div class="row justify-content-md-center">
                            <span class="col"></span>
                            <span class="col-sm-auto col-md-auto col-lg-auto col-xl-auto">
                                <a
                                    href="javascript:;"
                                    title="编辑"
                                    class="mr-1 col-1"
                                    onClick={() => this.showModal(row)}
                                >
                                    <i class="fa fa-edit" style="color: #69aa46;"></i>
                                </a>
                                {row.status == 2 ? (
                                    <a
                                        href="javascript:;"
                                        title="启用"
                                        class="mr-1 col-1"
                                        onClick={() => this.Enable(row)}
                                    >
                                        <i class="fa fa-check-circle" style="color: #69aa46;"></i>
                                    </a>
                                ) : (
                                    <a
                                        href="javascript:;"
                                        title="禁用"
                                        class="mr-1 col-1"
                                        onClick={() => this.Disable(row)}
                                    >
                                        <i class="fas fa-ban" style="color: #dd5a43;"></i>
                                    </a>
                                )}
                                <a
                                    href="javascript:;"
                                    title="删除"
                                    class="mr-1 col-1"
                                    onClick={() => this.DeleteItem(row)}
                                >
                                    <i class="fa fa-trash-alt" style="color: #dd5a43;"></i>
                                </a>
                            </span>
                            <span class="col"></span>
                        </div>
                    );
                }
            }
        ];

        //表格 头部 可伸缩
        this.components = components(columns);
        this.detailComponents = components(detailColumns);
        return {
            fileList: [],
            basePostData: {},
            postData: {},
            data: [],
            detailData: [],
            count: 0,
            header: { "Access-Token": Vue.ls.get("Access-Token") },
            columns,
            detailColumns,
            validateStatus: "success",
            isShow: "display:block",
            form: this.$form.createForm(this, { name: "advanced_search" }),
            errorMsg: null,
            isDisabled: false,
            pagination: {
                defaultPageSize: 10,
                current: 1,
                pageSize: 10,
                total: 0,
                showTotal: total => `共 ${total} 条数据`,
                showSizeChanger: true,
                showQuickJumper: true,
                pageSizeOptions: ["10", "20", "30", "40", "50"],
                showLessItems: true
            },
            show: false, //是否显示
            editItem: {}, //新增/编辑对象
            checkedOfficeKeys: [],

        };
    },
    created () {
        this.basePostData = {
            current: 1,
            size: 20,
            crmId: this.customerId
        };
        this.postData = { ...this.basePostData };
    },
    mounted () {
        this.PageList();
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
        //是否显示 新增按钮 
        addBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                customerId
                && (permissions.includes("crm:price:add")
                    || (crmType == 0 && permissions.includes("crm:clue:price:add"))
                    || (crmType == 1 && permissions.includes("crm:potential:price:add"))
                    || (crmType == 2 && permissions.includes("crm:deals:price:add"))
                )
            ) {
                isShow = true;
            }
            return isShow;
        },
        //是否显示 编辑按钮 
        editBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                permissions.includes("crm:price:edit")
                || (crmType == 0 && permissions.includes("crm:clue:price:edit"))
                || (crmType == 1 && permissions.includes("crm:potential:price:edit"))
                || (crmType == 2 && permissions.includes("crm:deals:price:edit"))
            ) {
                isShow = true;
            }
            return isShow;
        },
        //是否显示 删除按钮 
        disableBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                permissions.includes("crm:price:disable")
                || (crmType == 0 && permissions.includes("crm:clue:price:disable"))
                || (crmType == 1 && permissions.includes("crm:potential:price:disable"))
                || (crmType == 2 && permissions.includes("crm:deals:price:disable"))
            ) {
                isShow = true;
            }
            return isShow;
        },
    },
    methods: {
        //跳转到 客户详情
        goToDetail (item) {
            const { permissions } = this;
            if (!this.customerId && (permissions.includes("crm:potential:edit") || permissions.includes("crm:potential:edit") || permissions.includes("crm:deals:edit"))) {
                this.$router.push(`/crm/customer/detail/${item.crmName}/${item.crmId}/price`)
            }
        },
        uploadFile (info) {
            let fileList = [...info.fileList];
            //fileList = fileList.slice(-2);
            fileList = fileList.map(file => {
                if (file.response) {
                    file.url = file.response.url;
                    file.id = file.response.id;
                }
                return file;
            });
            this.fileList = fileList;
        },
        //添加
        AddItem () {
            this.editItem = {};
            this.fileList = [];
            this.detailData = [];
            this.$refs["edit-modal"].show();
        },
        //删除
        deletePrice (menu) {
          let _this = this;
          this.$confirm({
            title: '提示',
            content: '您确定要删除该字典吗？',
            onOk() {
              deletePrice({ id: menu.id }).then(response => {
                  if (response.code === 200) {
                      _this.$message.success("删除成功");
                      //刷新 列表
                      _this.PageList();
                  } 
              });
            },
            onCancel() {
            },
          });
        },
        // 获取列表
        PageList () {
            const { postData } = this;
            priceList(postData)
                .then(response => {
                    console.log("获取字典类型列表", response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records, total, current, size } = data;
                        this.data = records;
                        Object.assign(this.pagination, {
                            total
                        });
                    }
                })
                .catch(error => { });
        },
        Disable (item) {
            disable({ id: item.id })
                .then(response => {
                    if (response.code === 200) {
                      this.$message.success("禁用成功");
                      //刷新 列表
                      this.PageList();
                    } 
                })

        },
        Enable (item) {
            enable({ id: item.id })
                .then(response => {
                    if (response.code === 200) {
                      this.$message.success("启用成功");
                      //刷新 列表
                      this.PageList();
                    } 
                })

        },
        onDelete (key) {
          let _this = this;
          this.$confirm({
            title: '提示',
            content: '您确定要删除吗？',
            onOk() {
                const dataSource = [..._this.detailData];
                _this.detailData = dataSource.filter(item => item.key !== key);
            },
            onCancel() {
            },
          });
        },
        handleAdd () {
            const { count, detailData } = this;
            const newData = {
                key: count,
                commodityName: "",
                price: "",
                discount: "",
                counts: "",
                specs: "",
                totalPrice: ""
            };
            this.detailData = [...detailData, newData];
            this.count = count + 1;
        },
        //获取
        showFunction () {
            this.show = !this.show;
        },
        showModal (editItem) {
            console.log("editItem", editItem);
            this.editItem = { ...editItem };
            this.$refs["edit-modal"].show();
        },
        hideModal () {
            this.$refs["edit-modal"].hide();
        },
        handleReset () {
            this.form.resetFields();
        },
        handleSubmit (e) {
            e.preventDefault();
            this.form.validateFields((err, values) => {
                console.log("开始保存:", this.editItem);
                if (!err) {
                    save(this.editItem)
                        .then(response => {
                            if (response.code === 200) {
                                this.$message.success("保存成功");
                                //刷新 列表
                                this.PageList();
                                this.hideModal();
                            }
                        })

                }
            });
        },
        onTableChange (pagination, filters, sorter) {
            Object.assign(this.postData, {
                current: pagination.current,
                size: pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            this.PageList();
        },
        reset () {
            const { basePostData } = this;
            this.postData = { ...basePostData };
        },
        onCellChange (key, dataIndex, value) {
            const dataSource = [...this.detailData];
            const target = dataSource.filter(item => key === item.key)[0];
            if (target) {
                target[dataIndex] = value;
                this.detailData = dataSource;
            }
        }
    },
    watch: {
        "customerId": function (n, o) {
            console.log("price_客户ID改变:", n, o);
            const { basePostData } = this;
            basePostData.crmId = n;
            this.reset();
            this.PageList();
            this.selectedKeys = [];
        }
    }
};
</script>
<style scoped>
    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .icons-list >>> .anticon {
        margin-right: 8px;
        font-size: 16px;
    }
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }

    /* tile uploaded pictures */
    .upload-list-inline >>> .ant-upload-list-item {
        float: left;
        width: 200px;
        margin-right: 8px;
    }
    .upload-list-inline >>> .ant-upload-animate-enter {
        animation-name: uploadAnimateInlineIn;
    }
    .upload-list-inline >>> .ant-upload-animate-leave {
        animation-name: uploadAnimateInlineOut;
    }
    .ant-popover-inner {
        z-index: 2999;
    }
    /* .crm-btn {
      margin-left: 10px;
      margin-bottom: 10px;
    } */
</style>
